import CITY from '../../../components/newcity.min';
import getIn from '../../../../../yali-sdk/utils/getIn';
import { SUCCESS } from '../../../../../yali-sdk/utils/success';
import { FAIL } from '../../../../../yali-sdk/utils/fail';
import addressDetail from '../../../../../yali-sdk/business/address/addressDetail';
import saveAddress from '../../../../../yali-sdk/business/address/saveAddress';
import updateAddress from '../../../../../yali-sdk/business/address/updateAddress';
import addressDelete from '../../../../../yali-sdk/business/address/addressDelete';
import { IdentityPhone, VerifyPhoneOrTel, IdentityZipCode } from '../../../../config/validateTools';
import { notify } from '../../../../../yali-sdk/utils/NotifyRegistryCenter';
import { showFail, showSuccess } from '../../../../config/common';
import { MEMBER_ADDRESS_LIST_PATH } from '../../../pathUrl';
import QQMapWX from '../../../../../yali-sdk/lib/qqmap-wx-jssdk.min.js';
const gRegion = CITY.region;
const configPage = {
    data: {
        address: undefined, // 详细地址
        visible: false,
        provinceId: undefined,
        cityId: undefined,
        zoneId: undefined,
        isDefault: false,
        realname: undefined,
        phone: undefined, // 手机号
        reginValue: '', // 地区
        id: undefined, // 有id代表是编辑
    },
    onLoad(option) {
        const id = getIn(option, ['id']);
        const token = getIn(getApp(), ['globalData', 'token']);
        if (id) {
          global.ActionDispatcher.execute(addressDetail, { token, id }, (status, result) => {
            if (status == SUCCESS) {
              const _object = result.data;
              const isDefault = Number(getIn(_object, ['is_default'])) == 1;
              const realname = getIn(_object, ['realname']);
              const phone = getIn(_object, ['phone']);
              const address = getIn(_object, ['address']);
              const provinceId = getIn(_object, ['province']);
              const cityId = getIn(_object, ['city']);
              const zoneId = getIn(_object, ['zone']);
              const reginValue = `${getIn(_object, ['province_name'])}，${getIn(_object, ['city_name'])}，${getIn(_object, ['zone_name'])}`;
              this.setData({
                realname, phone, address, isDefault, provinceId, cityId, zoneId, reginValue, id,
              });
            }
          });
        } else {// 默认当前地区
          wx.showLoading();
          // 获取当前位置
          const qqmapsdk = new QQMapWX({
            key: 'PMFBZ-RANLG-C4OQT-IKVXS-PO3FQ-D5FEO' // 必填
          });
          wx.getLocation({
            type: 'wgs84',
            success: (res) => {
              const latitude = res.latitude
              const longitude = res.longitude
              qqmapsdk.reverseGeocoder({
                location: {
                  latitude: res.latitude,
                  longitude: res.longitude
                },
                success: (addressRes) => {
                  const ad_info = getIn(wx.getStorageSync('location'), ['ad_info']);
                  const reginValue = `${ad_info.province}，${ad_info.city}，${ad_info.zone}`;
                  let provinceId = null, cityId = null, zoneId = null;
                  Object.keys(gRegion).map((p) => {
                    if (gRegion[p].name == ad_info.province) {
                      provinceId = gRegion[p].id;
                      Object.keys(gRegion[p].child).map((c) => {
                        if (gRegion[p].child[c].name == ad_info.city) {
                          cityId = gRegion[p].child[c].id;
                          Object.keys(gRegion[p].child[c].child).map((z) => {
                            if (gRegion[p].child[c].child[z].name == ad_info.zone) {
                              zoneId = gRegion[p].child[c].child[z].id;
                            }
                          })
                        }
                      })
                    }
                  });
                  wx.hideLoading();
                  this.setData({ reginValue, provinceId, cityId, zoneId });
                }
              });
            }
          })
        }
    },
    onSaveAddress() {
        const { id } = this.data;
        const { realname } = this.data;
        const { phone } = this.data;
        const province = this.data.provinceId;
        const city = this.data.cityId;
        const zone = this.data.zoneId;
        const { address } = this.data;
        const is_default = this.data.isDefault ? 1 : 0;
        const token = getIn(getApp(), ['globalData', 'token']);
        if (!token) {
            showFail('请先登录再操作');
            return;
        }
        if (!realname) {
            showFail('请填写姓名');
            return;
        }
        if (this.getStringLength(realname) > 15) {
            showFail('填写的姓名不能超过15个字符');
            return;
        }
        if (!phone) {
            showFail('请填写手机号码');
            return;
        }
        if (!IdentityPhone(phone)) {
            showFail('请填写正确的手机号码');
            return;
        }
        if (!province || !city || !zone) {
            showFail('请选择地区');
            return;
        }
        if (!address || (address.trim && address.trim().length < 1)) {
            showFail('请输入详细地址');
            return;
        }
        if (this.getStringLength(address) > 50) {
            showFail('填写的详细地址不能超过50个字符');
            return;
        }
        wx.showLoading();
        let params = {
            realname, phone, province, city, zone, address, is_default, token,
        };
        if (id) {
            params = { ...params, id };
            global.ActionDispatcher.execute(updateAddress, params, (status, result) => {
              if (status == SUCCESS) {
                wx.hideLoading();
                notify && notify('updateAddressList');
                global.navigateHelper && global.navigateHelper.navigateBack();
              } else if (status == FAIL) {
                wx.hideLoading();
                showFail('修改地址失败');
              }
            });
        } else {
          global.ActionDispatcher.execute(saveAddress, params, (status, result) => {
            if (status == SUCCESS) {
              wx.hideLoading();
              notify && notify('updateAddressList');
              global.navigateHelper && global.navigateHelper.navigateBack();
            } else if (status == FAIL) {
              wx.hideLoading();
              showFail('添加地址失败');
            }
          });
        }
        
    },
    getStringLength(str) {
        let len = 0;
        if (!str || !str.charCodeAt) {
            return len;
        }
        for (let i = 0; i < str.length; i++) {
            if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
                len += 2;
            } else {
                len += 1;
            }
        }
        return len;
    },
    /** 删除 */
    delAddress(e) {
      const id = this.data.id;
      const token = getIn(getApp(), ['globalData', 'token']);
      wx.showModal({
        title: '提示',
        content: '确认删除这条记录吗',
        success: (res) => {
          if (res.confirm) {
            global.ActionDispatcher.execute(addressDelete, { token, id }, (status, result) => {
              if (status == SUCCESS) {
                showSuccess('删除地址成功');
                notify && notify('updateAddressList');
                global.navigateHelper && global.navigateHelper.navigateBack();
              } else if (status == FAIL) {
                showFail((result && result.msg) || '删除地址失败');
              }
            });
          }
        },
      });
    },
    onChangeName(e) {
        this.data.realname = getIn(e, ['detail', 'value']);
    },
    onChangePhone(e) {
        this.data.phone = getIn(e, ['detail', 'value']);
    },
    onChangeAddress(e) {
        this.setData({ address: getIn(e, ['detail', 'value']) });
    },

    onChangeRegin(e) {
        const reginValue = getIn(e, ['detail', 'address']);
        const provinceId = getIn(e, ['detail', 'provinceId']);
        const cityId = getIn(e, ['detail', 'cityId']);
        const zoneId = getIn(e, ['detail', 'zoneId']);
        this.setData({
            reginValue, provinceId, cityId, zoneId, visible: false,
        });
    },
    setDefault(e) {
        const isDefault = getIn(e, ['detail', 'value']);
        this.setData({ isDefault });
    },
    showReginPicker() {
        this.setData({ visible: true });
    },
    // 打开地图定位当前位置
    openMap() {
      wx.getLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: (res) => {
          var latitude = res.latitude
          var longitude = res.longitude
          wx.chooseLocation({
            success: (res) => {
              this.setData({ address: res.address });
            }
          })
        }
      })
    }
};
Page(configPage);
